# -*- coding: UTF-8 -*-
from django.shortcuts import render, redirect, get_object_or_404

from django.shortcuts import render
from django.conf import settings

# Create your views here.
from django.http import JsonResponse,HttpResponse

from django.contrib.auth.decorators import login_required
from .salt_api import SaltAPI
from django.template.context_processors import request

@login_required()
def key_list(request):
    SALTAPI = SaltAPI(url=settings.SALT_API_URL, username=settings.SALT_API_USER, password=settings.SALT_API_PASSWD)
    if request.method =="GET":
        allkeys=SALTAPI.list_all_key()
        accept_keys=allkeys[0]
        pre_keys=allkeys[1]
        return render(request,"saltstack/key_list.html",locals())
    elif request.method =="POST":
        option=request.POST.get('option','')
        if option =="key_del":
            node_name=request.POST.get('serverid')
            func_rst=SALTAPI.delete_key(node_name)
            func_rst=func_rst[0]['data']['success']
            if not func_rst:
                return JsonResponse({"msg":"删除key失败"})
            return JsonResponse({"msg":"删除key成功"})

        elif option=="accept_key":
            node_name = request.POST.get('serverid')
            func_rst = SALTAPI.accept_key(node_name)
            func_rst = func_rst[0]['data']['success']
            if not func_rst:
                return JsonResponse({"msg":"Accept key失败"})
            return JsonResponse({"msg":"Accept key成功"})



@login_required()
def common_operation(request):
    SALTAPI = SaltAPI(url=settings.SALT_API_URL, username=settings.SALT_API_USER, password=settings.SALT_API_PASSWD)
    if request.method == "GET":
        allkeys = SALTAPI.list_all_key()
        accept_keys = allkeys[0]
        pre_keys = allkeys[1]
        return render(request, "saltstack/salt_opreation.html", locals())